package com.zzf.concurrent.example.design.pattern.guarded.suspension;

import lombok.extern.slf4j.Slf4j;

/**
 * @author GaoFeng2017
 * @date 2019/9/8 9:51
 */
@Slf4j
public class ServerThread<T> extends Thread {

    private RequestQueue<T> requestQueue;
    private volatile boolean isClosed;

    public ServerThread(RequestQueue<T> requestQueue) {
        this.requestQueue = requestQueue;
        this.isClosed = false;
    }

    @Override
    public void run() {

        // 此处有三处中断
        // 循环执行完后中断，此时isClosed被改变
        // sleep被中断
        // get被中断
        while (!isClosed) {
            T data = requestQueue.get();
            if (data == null) {
                log.info("get empty data!");
                continue;
            }

            log.info("get data from request queue -> {}", data);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.info("stop receive data...");
                return;
            }
        }
    }

    public void shutdown() {
        this.isClosed = true;
        this.interrupt();
    }
}
